//
//  MainLoginViewController.m
//  EasyToo
//
//  Created by hydb on 13-6-11.
//
//

#import "MainLoginViewController.h"
#import "LoginViewController.h"
#import "RegisterViewController.h"
#import "AccountManager.h"
#import "LeveyTabBarController.h"
#import <QuartzCore/QuartzCore.h>

@interface MainLoginViewController ()

@end

@implementation MainLoginViewController
{
    UIAlertView *_baseAlert;
    
    UIImageView *_imgview;
    UITextField *_nameTF;
    UITextField *_passwordTF;
    UIButton *_loginBtn;
    UIButton *_registerBtn;
    UIButton *_getpassbacBtn;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    [self.navigationItem setTitle:@"用户登陆"];
    //初始化视图
    [self init_view];
}

- (void)dealloc
{
    [_imgview release];
    [_nameTF release];
    [_passwordTF release];
    [_loginBtn release];
    [_registerBtn release];
    [_getpassbacBtn release];
    
    _imgview = nil;
    _nameTF = nil;
    _passwordTF = nil;
    _loginBtn = nil;
    _registerBtn = nil;
    _getpassbacBtn = nil;
    
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}





//初始化视图
- (void)init_view
{
    //定义title
    self.title = @"登录/注册";
    //加载背影
    [self.view setBackgroundColor:BackgroundColor];
    
    //头像显示
    _imgview = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"1.png"]];
    _imgview.frame = CGRectMake(120, ADJUST_IOS7STATUES_HIGHT+80, 80, 80);
    [self.view addSubview:_imgview];
    
    //说明
    NSUserDefaults *_userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *username = [_userDefaults valueForKey:@"userName"];
    
    //用户名
    _nameTF = [[UITextField alloc] initWithFrame:CGRectMake(20, ADJUST_IOS7STATUES_HIGHT+170, 280, 50)];
    _nameTF.font = [UIFont fontWithName:@"Arial" size:18.0f];
    _nameTF.textColor = [UIColor blackColor];
    _nameTF.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _nameTF.borderStyle = UITextBorderStyleRoundedRect;
    _nameTF.delegate = self ;
    _nameTF.returnKeyType =UIReturnKeyDone;
    _nameTF.layer.borderColor = [UIColor grayColor].CGColor;
    _nameTF.layer.borderWidth = 1 ;
    _nameTF.layer.cornerRadius = 10 ;
    _nameTF.keyboardType = UIKeyboardTypeNumberPad;
    _nameTF.placeholder = [NSString stringWithFormat:@"手机号码"];
    _nameTF.text = username;
    _nameTF.clearsOnBeginEditing = YES;
    [self.view addSubview:_nameTF];
    
    //密码
    _passwordTF = [[UITextField alloc] initWithFrame:CGRectMake(20, ADJUST_IOS7STATUES_HIGHT+230, 280, 50)];
    _passwordTF.font = [UIFont fontWithName:@"Arial" size:18.0f];
    _passwordTF.textColor = [UIColor blackColor];
    _passwordTF.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _passwordTF.borderStyle = UITextBorderStyleRoundedRect;
    _passwordTF.delegate = self ;
    _passwordTF.returnKeyType =UIReturnKeyDone;
    _passwordTF.layer.borderColor = [UIColor grayColor].CGColor;
    _passwordTF.layer.borderWidth = 1 ;
    _passwordTF.layer.cornerRadius = 10 ;
    _passwordTF.placeholder = [NSString stringWithFormat:@"登录密码"];
    //    if (!username) {
    //        _passwordTF.text = [_userDefaults valueForKey:@"passWord"];
    //    }
    [_passwordTF setSecureTextEntry:YES];
    [self.view addSubview:_passwordTF];
    
    //注册
    _registerBtn = [[UIButton alloc]initWithFrame:CGRectMake(20, ADJUST_IOS7STATUES_HIGHT+290, 130, 40)];
    [_registerBtn setBackgroundImage:[UIImage imageNamed:@"index_1.png"] forState:UIControlStateNormal];
    [self.view addSubview:_registerBtn];
    [_registerBtn addTarget:self action:@selector(registerEvent) forControlEvents:UIControlEventTouchUpInside];
    
    //登录
    _loginBtn = [[UIButton alloc]initWithFrame:CGRectMake(170, ADJUST_IOS7STATUES_HIGHT+290, 130, 40)];
    [_loginBtn setBackgroundImage:[UIImage imageNamed:@"index_2.png"] forState:UIControlStateNormal];
    [self.view addSubview:_loginBtn];
    [_loginBtn addTarget:self action:@selector(loginEvent) forControlEvents:UIControlEventTouchUpInside];
    
    //找回密码
    _getpassbacBtn = [[UIButton alloc]initWithFrame:CGRectMake(190, ADJUST_IOS7STATUES_HIGHT+340, 150, 20)];
    [_getpassbacBtn setTitle:@"忘记密码？" forState:UIControlStateNormal];
    _getpassbacBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [_getpassbacBtn setBackgroundColor:[UIColor clearColor]];
    [_getpassbacBtn setTitleColor:[UIColor grayColor]forState:UIControlStateNormal];
    [self.view addSubview:_getpassbacBtn];
    [_getpassbacBtn addTarget:self action:@selector(getpassbacEvent) forControlEvents:UIControlEventTouchUpInside];
    
}

//找回密码
- (void)getpassbacEvent
{
    if ([_nameTF.text isEqualToString:@""]) {
        _baseAlert = [[UIAlertView alloc]  initWithTitle:@"登录出错" message:@"用户名或密码不能为空"  delegate:self cancelButtonTitle:@"返回" otherButtonTitles: nil];
        [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(performDismiss:) userInfo:nil repeats:NO];
        [_baseAlert show];
    }
    
    else if ([DeviceUtil isMobileNumber:_nameTF.text] == NO)
    {
        _baseAlert = [[UIAlertView alloc]  initWithTitle:@"注册出错" message:@"手机号格式出错"  delegate:self cancelButtonTitle:@"返回" otherButtonTitles: nil];
        [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(performDismiss:) userInfo:nil repeats:NO];
        [_baseAlert show];
    }
    
    else {
        RegisterViewController *registerView = [[RegisterViewController alloc] init];
        registerView.mobile = _nameTF.text;
        registerView.type = 2;
        [self.navigationController pushViewController:registerView animated:YES];
        [registerView release];
    }
}


//登录
- (void)loginEvent
{
    [_nameTF resignFirstResponder];
    [_passwordTF resignFirstResponder];
    
    //检测用户名密码是否为空
    if ([_nameTF.text isEqualToString:@""] == YES || [_passwordTF.text isEqualToString:@""] == YES) {
        _baseAlert = [[UIAlertView alloc]  initWithTitle:@"登录出错" message:@"用户名或密码不能为空"  delegate:self cancelButtonTitle:@"返回" otherButtonTitles: nil];
        [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(performDismiss:) userInfo:nil repeats:NO];
        [_baseAlert show];
    }
    
    //判断手机号码格式
    else if ([DeviceUtil isMobileNumber:_nameTF.text] == NO) {
        _baseAlert = [[UIAlertView alloc]  initWithTitle:@"注册出错" message:@"手机号格式出错"  delegate:self cancelButtonTitle:@"返回" otherButtonTitles: nil];
        [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(performDismiss:) userInfo:nil repeats:NO];
        [_baseAlert show];
    }
    
    //成功登录
    else{
        AccountManager *accountmanager = [AccountManager shareManager];
        accountmanager.delegate = self;
        
        [accountmanager resetPasswd:_nameTF.text password:_passwordTF.text cardId:@"" apiCode:@"999010"];
        //[accountmanager login:_nameTF.text Password:_passwordTF.text];
    }
    
}


- (void) performDismiss: (NSTimer *)timer {
    [_baseAlert dismissWithClickedButtonIndex:0 animated:NO];//important
    [_baseAlert release];
    _baseAlert = NULL;
}


//注册
- (void)registerEvent
{
    NSUserDefaults *_userDefaults = [NSUserDefaults standardUserDefaults];
    [_userDefaults setValue:_nameTF.text forKey:@"userName"];
    [_userDefaults synchronize];
    
    RegisterViewController *registerView = [[RegisterViewController alloc] init];
    registerView.mobile = _nameTF.text;
    registerView.type = 1;
    [self.navigationController pushViewController:registerView animated:YES];
    [registerView release];
}


//开始编辑输入框的时候，软键盘出现，执行此事件
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    CGRect frame = textField.frame;
    int offset = frame.origin.y + 32 - (self.view.frame.size.height - 216.0);//键盘高度216
    
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    
    //将视图的Y坐标向上移动offset个单位，以使下面腾出地方用于软键盘的显示
    if(offset > 0)
        self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);
    
    [UIView commitAnimations];
}


//输入框编辑完成以后，将视图恢复到原始状态
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
}


#pragma mark UITextFieldDelegate
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [_nameTF resignFirstResponder];
    [_passwordTF resignFirstResponder];
}

#pragma networking
- (void)resetPasswd:(BOOL)isSuccess
              point:(NSString*)point
{
    if (isSuccess) {
        NSUserDefaults *_userDefaults = [NSUserDefaults standardUserDefaults];
        [_userDefaults setBool:YES forKey:@"isLogin"];
        [_userDefaults setValue:_nameTF.text forKey:@"userName"];
        [_userDefaults setValue:_passwordTF.text forKey:@"passWord"];
        [_userDefaults synchronize];
        
        LoginViewController *loginViewController=[[LoginViewController alloc] init];
        [self.navigationController pushViewController:loginViewController animated:YES];
        [loginViewController release];
        //        [self.leveyTabBarController setSelectedIndex:0];
        //        return;
    } else {
        _baseAlert = [[UIAlertView alloc]  initWithTitle:@"登录失败" message:@"请埴写正确的用户名密码，谢谢"  delegate:self cancelButtonTitle:@"返回" otherButtonTitles: nil];
        [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(performDismiss:) userInfo:nil repeats:NO];
        [_baseAlert show];
    }
}



////用户登录
//- (void)loginUser:(BOOL)isSuccess accstatus:(NSString*)accstatus
//{
//    if (isSuccess) {
//        NSUserDefaults *_userDefaults = [NSUserDefaults standardUserDefaults];
//        [_userDefaults setBool:YES forKey:@"isLogin"];
//        [_userDefaults setValue:_nameTF.text forKey:@"userName"];
//        [_userDefaults setValue:_passwordTF.text forKey:@"passWord"];
//        [_userDefaults synchronize];
//        [self.leveyTabBarController setSelectedIndex:0];
//        return;
//    } else {
//        _baseAlert = [[UIAlertView alloc]  initWithTitle:@"登录失败" message:@"请埴写正确的用户名密码，谢谢"  delegate:self cancelButtonTitle:@"返回" otherButtonTitles: nil];
//        [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(performDismiss:) userInfo:nil repeats:NO];
//        [_baseAlert show];
//    }
//}

@end
